package org.restorator.controller;

import com.google.gson.Gson;
import org.restorator.entity.Item;
import org.restorator.entity.Order;
import org.restorator.service.ItemService;
import org.restorator.service.impl.ItemServiceImpl;
import org.restorator.utill.ControllerUtil;
import org.restorator.utill.GeneralUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.annotation.WebInitParam;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 *
 * Controlle for work with REST style requests on entity {@link Item}.
 * @author Snisar Bogdan.
 */
@WebServlet(name = "itemAllController", urlPatterns = "/item")
public class ItemAllController extends HttpServlet {

    private static Logger logger = LoggerFactory.getLogger(GeneralUtil.getClassName());

    private ItemService itemService;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        itemService = new ItemServiceImpl();
    }



    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            List<Item> items = itemService.getAll();
            resp.setContentType("application/json");

            if(items != null && !items.isEmpty()) {
                logger.debug("Get request. Context path {}. Request URI - {}", req.getContextPath(), req.getRequestURI());
                logger.trace("Items {}", items);
                ControllerUtil.printOk(resp.getWriter(), items);
            } else{
                logger.debug("Get request. Context path {}. Request URI - {}", req.getContextPath(), req.getRequestURI());
                logger.trace("Items {}", items);
                ControllerUtil.printError(resp);
            }
            
        } catch (Exception e) {
            logger.error("Exception in request processing: {}. \nStack trace: {}", e.getMessage(), e);
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

}
